package com.six666.medicaldevicetestingsystem.service.impl;

import com.six666.medicaldevicetestingsystem.service.Excel_Service;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.apache.poi.ss.usermodel.CellType.*;

@Service
public class Excel_Service_Impl implements Excel_Service {
    public String uploadDir;

    @Autowired
    public void FileStorageService(Environment env) {
        this.uploadDir = env.getProperty("file.upload-dir");
    }
    public List<List<String>> readExcelFile(String filePath) throws IOException {
        List<List<String>> data = new ArrayList<>();
        FileInputStream fis = new FileInputStream(filePath);
        Workbook workbook = new XSSFWorkbook(fis);
        Sheet sheet = workbook.getSheetAt(0); // 读取第一个Sheet

        for (Row row : sheet) {
            List<String> rowData = new ArrayList<>();
            for (Cell cell : row) {
                switch (cell.getCellType()) {
                    case STRING:
                        rowData.add(cell.getStringCellValue());
                        break;
                    case NUMERIC:
                        if (DateUtil.isCellDateFormatted(cell)) {
                            rowData.add(cell.getDateCellValue().toString());
                        } else {
                            rowData.add(String.valueOf(cell.getNumericCellValue()));
                        }
                        break;
                    case BOOLEAN:
                        rowData.add(String.valueOf(cell.getBooleanCellValue()));
                        break;
                    case FORMULA:
                        FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
                        CellValue cellValue = evaluator.evaluate(cell);
                        if (cellValue.getCellType()==STRING) {
                            rowData.add(cellValue.getStringValue());
                        }
                        else if(cellValue.getCellType()==NUMERIC){
                            rowData.add(String.valueOf(cellValue.getNumberValue()));
                        }
                        else if(cellValue.getCellType()==BOOLEAN){
                            rowData.add(String.valueOf(cellValue.getBooleanValue()));
                        }
                        else if(cellValue.getCellType()==ERROR){
                            rowData.add(cell.getCellFormula());
                        }
                        else{
                            rowData.add(cell.getCellFormula());
                        }
                        break;
                    case BLANK:
                        rowData.add("");
                        break;
                    default:
                        rowData.add("UNKNOWN");
                }
            }
            data.add(rowData);
        }

        workbook.close();
        fis.close();

        return data;
    }
    @Override
    public <T> void exportListToExcel(List<T> list, String[] headers, String filePath) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        // 创建表头行
        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }
        // 假设列表中的元素是Map类型，且Map的key与headers数组对应
        int rowNum = 1;
        for (T item : list) {
            if (item instanceof Map) {
                Map<String, Object> mapItem = (Map<String, Object>) item;
                Row row = sheet.createRow(rowNum++);
                for (int i = 0; i < headers.length; i++) {
                    Cell cell = row.createCell(i);
                    Object value = mapItem.get(headers[i]);
                    if (value != null) {
                        cell.setCellValue(value.toString());
                    }
                }
            } else {
                throw new IllegalArgumentException("Unsupported list item type: " + item.getClass().getName());
            }
        }

        // 自动调整列宽
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }

        // 将工作簿写入文件
        try (FileOutputStream fileOut = new FileOutputStream(filePath)) {
            workbook.write(fileOut);
        }
        // 关闭工作簿
        workbook.close();
    }
}
